#include "TcpServer.hpp"
#include "InetAddr.hpp"
#include "Comm.hpp"
#include "Translate.hpp"
#include "Daemon.hpp"
#include <cctype>
#include <memory>

void Ping(int sockfd, InetAddr addr)
{
    std::string massage = "Pong";
    int n = write(sockfd, massage.c_str(), massage.size());
    if (n > 0)
    {
        lg(Debug, "service success , client : [%s] , service : %s\n , sockfd : %d", addr.ToString().c_str(), "ping", sockfd);
    }
    else if (n == 0)
    {
        lg(Debug, "client quit....\n");
    }
    else
    {
        lg(Error, "write success , errno : %d ,  strerror : %s\n", errno, strerror(errno));
    }
}

Translate ts;

void Translate(int sockfd, InetAddr addr)
{
    lg(Debug, "selete servlet : %s , sockfd : %d  cilent info : %s", "Translate\n", sockfd, addr.ToString().c_str());
    char English[128];
    int n = read(sockfd, English, sizeof(English));
    if (n > 0)
        English[n] = 0;
    std::string chinese = ts.Excute(English);
    write(sockfd, chinese.c_str(), chinese.size());
    lg(Debug, "Translate  English : %s ----- > chinese : %s\n", English, chinese.c_str());
} 


//输入转换为大写
void Conversion(int sockfd, InetAddr addr)
{
    char strbuff[1024];
    int n = read(sockfd, strbuff, sizeof(strbuff));
    if(n > 0)
        strbuff[n] = 0;
    std::string result = strbuff;
    for(auto& ch : result)
    {
        ch = std::toupper(static_cast<unsigned char>(ch));
    }
    write(sockfd, result.c_str(), result.size());
    lg(Debug, "Conversion success !!!  result str : %s", result.c_str());
}

void Usage(std::string proc)
{
    std::cout << "Usage : \n\t" << proc << " local_port" << std::endl;
    exit(Usage_Err);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
    }
    uint16_t port = std::atoi(argv[1]);
    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>(port);
    lg.Enable(ClassFile);
    //变为守护进程
    Daemon(false,false);

    tsvr->Init();
    // 注册服务
    tsvr->RegistrationServices("ping", Ping);
    tsvr->RegistrationServices("translate", Translate);
    tsvr->RegistrationServices("conversion", Conversion);
    tsvr->Start();

    return 0;
}